package com.example.java_chatroom.api;

import com.example.java_chatroom.model.Friend;
import com.example.java_chatroom.model.MessageSession;
import com.example.java_chatroom.model.MessageSessionMapper;
import com.example.java_chatroom.model.User;
import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
public class MessageSessionAPI {
    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @GetMapping("/sessionList")
    public Object getMessageSessionList(HttpServletRequest req) {
        List<MessageSession> messageSessionList = new ArrayList<>();
        // 1. 获取到当前用户的 userId (从 spring 的 session 中获取)
        HttpSession session = req.getSession(false);
        if (session == null) {
            System.out.println("[getMessageSessionList] session == null!");
            return messageSessionList;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            System.out.println("[getMessageSessionList] user == null!");
            return messageSessionList;
        }
        // 2. 根据 userId 查询数据库, 查出来有哪些会话 id
        List<Integer> sessionIdList = messageSessionMapper.getSessionIdByUserId(user.getUserId());
        for (int sessionId : sessionIdList) {
            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(sessionId);
            // 3. 遍历会话 id, 查询出每个会话里涉及到的好友都有谁
            List<Friend> friends =
                    messageSessionMapper.getFriendsBySessionId(sessionId, user.getUserId());
            messageSession.setFriends(friends);
            // 4. 遍历会话 id, 查询出每个会话里最后一条消息 TODO (需要把后面的消息表构造好)
            messageSession.setLastMessage("晚上吃啥");
            messageSessionList.add(messageSession);
        }
        // 最终目标, 就是构造出一个 MessageSession 对象数组
        return messageSessionList;
    }
}
